<script lang="ts" setup>
import { FormInstance, FormRules, ElRow, ElCol, ElAutocomplete, ElForm, ElFormItem, ElInput, ElSwitch } from 'element-plus'
import { Menu, addMenuApi, updateMenuApi } from '/@/api/auth/menu'
import { CreateEditDialog, EditDialogType } from '/@/components/QsEditDialog'
import VabIconSelector from '/@/plugins/VabIconSelector/index.vue'
import { baseMessage } from '/@/utils/message'

const formRef = ref<FormInstance>()
const updateId = ref<number>()
const parentTitle = ref<string>()
const emit = defineEmits(['refresh'])
const form = ref<Omit<Menu, 'id'>>({
  sort: 0,
  type: 1,
  parentId: 0,
  name: '',
  path: '',
  component: '',
  redirect: '',
  status: 1,
  meta: {
    title: '',
    icon: '',
    hidden: false,
    noClosable: false,
    noColumn: false,
    noKeepAlive: false,
    dot: false,
    breadcrumbHidden: false,
    levelHidden: false,
  },
  menuName: '',
  level: 1,
  permission: '',
})
const confirm = async (type: EditDialogType) => {
  await formRef.value?.validate().then(async () => {
    if (type == EditDialogType.ADD || type == EditDialogType.SUBLEVEL) {
      const { result } = await addMenuApi(form.value)
      if (result) {
        baseMessage('添加成功')
      }
    } else {
      if (!updateId.value) return
      const { result } = await updateMenuApi(updateId.value, form.value)
      if (result[0]) {
        baseMessage('修改成功')
      }
    }
  })
}

const { open, type, Dialog } = new CreateEditDialog<Menu>({
  width: '800px',
  title: '菜单',
  confirm: confirm,
  closeCallback: () => {
    formRef.value?.resetFields()
    parentTitle.value = undefined
    form.value.parentId = 0
  },
  openCallBack: ({ data, type }) => {
    if (data) {
      if (type == EditDialogType.EDIT || type == EditDialogType.COPY) {
        updateId.value = data.id
        form.value = data
      } else if (type == EditDialogType.SUBLEVEL) {
        form.value.parentId = data.id
        parentTitle.value = data.meta.title
      }
    }
  },
  refresh: () => emit('refresh'),
})
export type ShowEditDialog = typeof open

const handleIcon = (item: string) => {
  form.value.meta.icon = item
}

const restaurants = ref<{ value: string }[]>([
  {
    value: 'Layout',
  },
  {
    value: '/@/view/',
  },
])
const createFilter = (queryString: string) => {
  return (restaurant: { value: string }) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}
const querySearch = (queryString: string, cb: any) => {
  const results = queryString ? restaurants.value.filter(createFilter(queryString)) : restaurants.value
  cb(results)
}
const rules: FormRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    {
      pattern: /^[A-Z]/,
      message: '必须大写字母开头',
      trigger: 'change',
    },
  ],
  path: [{ required: true, message: '请输入路径', trigger: 'blur' }],
  component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  'meta.title': [{ required: true, message: '请输入标题', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
}
defineExpose({
  open,
})
</script>

<template>
  <Dialog>
    <ElForm ref="formRef" label-width="120px" :model="form" :rules="rules">
      <ElRow :gutter="40">
        <ElCol v-if="type == EditDialogType.SUBLEVEL" :span="11">
          <ElFormItem label="父级" prop="parentId">
            <ElInput v-model="parentTitle" disabled />
          </ElFormItem>
        </ElCol>
        <ElCol :span="11">
          <ElFormItem label="标题" prop="meta.title">
            <ElInput v-model="form.meta.title" placeholder="请输入标题" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="11">
          <ElFormItem label="菜单名称" prop="name">
            <ElInput v-model="form.name" placeholder="请输入菜单名称(name)" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="11">
          <ElFormItem label="路径" prop="path">
            <ElInput v-model="form.path" placeholder="请输入路径" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="11">
          <ElFormItem label="组件路径" prop="component">
            <ElAutocomplete
              v-model="form.component"
              class="w-full"
              :fetch-suggestions="querySearch"
              placeholder="请输入组件路径"
              @select="(item) => (form.component = item.value)"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="11">
          <ElFormItem label="重定向" prop="redirect">
            <ElInput v-model="form.redirect" placeholder="请输入重定向" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="11">
          <ElFormItem label="图标" prop="meta.icon">
            <ElPopover popper-class="icon-selector-popper " trigger="click" :width="500">
              <template #reference>
                <ElInput v-model="form.meta.icon" clearable placeholder="请选择图标" />
              </template>
              <VabIconSelector @handle-icon="handleIcon" />
            </ElPopover>
          </ElFormItem>
        </ElCol>
        <ElCol :span="11">
          <ElFormItem label="排序" prop="sort">
            <ElInput v-model="form.sort" placeholder="请输入排序" type="number" />
          </ElFormItem>
        </ElCol>
        <ElCol v-if="type !== EditDialogType.SUBLEVEL" :span="11" />
        <ElCol :span="7">
          <ElFormItem label="开启" prop="status">
            <ElSwitch v-model="form.status" :active-value="1" inactive-value="0" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="7">
          <ElFormItem label="隐藏" prop="meta.hidden">
            <ElSwitch v-model="form.meta.hidden" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="7">
          <ElFormItem label="缓存" prop="meta.noKeepAlive">
            <ElSwitch v-model="form.meta.noKeepAlive" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="7">
          <ElFormItem label="隐藏一级" prop="meta.levelHidden">
            <ElSwitch v-model="form.meta.levelHidden" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="7">
          <ElFormItem label="显示小红点" prop="meta.dot">
            <ElSwitch v-model="form.meta.dot" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="7">
          <ElFormItem label="隐藏侧边栏" prop="meta.noColumn">
            <ElSwitch v-model="form.meta.noColumn" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="7">
          <ElFormItem label="隐藏面包屑" prop="meta.breadcrumbHidden">
            <ElSwitch v-model="form.meta.breadcrumbHidden" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="7">
          <ElFormItem label="不可关闭标签" prop="meta.noClosable">
            <ElSwitch v-model="form.meta.noClosable" />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </Dialog>
</template>

<style lang="scss" scoped>
.el-col {
  margin-bottom: 20px;
}
</style>
